﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using LayuiAdmin.Models;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Code;
using DB;
using Models;

namespace LayuiAdmin.Controllers {
    [Authorize]
    public class HomeController : Controller {
        public IActionResult Index() {
            try {
                long UserId = Convert.ToInt64(HttpContext.User.Identity.GetValue(ClaimTypes.Sid));
                UserTypes userType = (UserTypes)(Convert.ToInt32(HttpContext.User.Identity.GetValue("UserType")));
                ViewData["Name"] = HttpContext.User.Identity.GetValue(ClaimTypes.Name);
                ViewData["Id"] = UserId;
                ViewData["userType"] = HttpContext.User.Identity.GetValue("UserType");

                CacheHelper cache = new CacheHelper();
                var menuList = cache.GetMenuList();

                if (userType == UserTypes.超级管理员) {
                    ViewBag.Menus = menuList;
                } else {
                    using (var context = new SqlServerDB()) {
                        var role = (from r in context.Roles
                                    join ur in context.UserToRole on r.Id equals ur.RoleId
                                    where ur.UserId == UserId select r).FirstOrDefault();

                        if (role != null) {
                            var moduleids = role.ModuleIds.Split(',');

                            List<long> ids = new List<long>();

                            foreach (var id in moduleids) {
                                if (long.TryParse(id, out long i)) {
                                    ids.Add(i);
                                }
                            }

                            var m = menuList.Where(w => ids.Contains(w.id)).ToList();

                            ViewBag.Menus = m;
                        }
                    }
                }
            } catch {

            }

            return View();
        }

        public IActionResult About() {
            using (var context = new SqlServerDB()) {
                long userId = Convert.ToInt64(HttpContext.User.Identity.GetValue(ClaimTypes.Sid));
                UserTypes userType = (UserTypes)Convert.ToInt32(HttpContext.User.Identity.GetValue("UserType"));

                if (userType == UserTypes.普通用户) {
                    var user = context.Users.FirstOrDefault(m => m.Id == userId);

                    if (user != null) {
                        CacheHelper cache = new CacheHelper();
                        var areas = cache.GetAreaList();

                        if (user.ProvinceId > 0) {
                            ViewBag.Province = areas.FirstOrDefault(m => m.id == user.ProvinceId);
                        }

                        if (user.CityId > 0) {
                            ViewBag.City = areas.FirstOrDefault(m => m.id == user.CityId);
                        }

                        ViewBag.User = user;

                        ViewBag.RecommendCount = context.Users.LongCount(m => m.ParentId == userId);
                        ViewBag.Total = context.Incomes.Where(m => m.UserId == userId && m.SystemType == SystemType.收入).Sum(m => m.IncomePrice);
                    }
                } else {
                    var admin = context.Users.FirstOrDefault(m => m.UserType == UserTypes.超级管理员);

                    if (admin != null) {
                        ViewBag.Total = context.Incomes.Where(m => m.UserId == admin.Id && m.SystemType == SystemType.收入).Sum(m => m.IncomePrice).ToString("C");
                        ViewBag.payTotal = context.Incomes.Where(m => m.UserId == admin.Id && m.SystemType == SystemType.支出).Sum(m => m.IncomePrice).ToString("C");

                        ViewBag.salesVol = context.Orders.Where(m => m.Status == OrderStatus.已发货).Sum(m => m.Count);
                        ViewBag.orderCount = context.Orders.Count(m => m.Status == OrderStatus.已发货);
                    }
                }
            }

            return View();
        }

        public IActionResult Contact() {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Privacy() {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error() {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public IActionResult Product() {
            using (var context = new SqlServerDB()) {
                var model = context.Products.FirstOrDefault();

                if (model != null) {
                    return View(model);
                }
            }

            return View();
        }

    }
}
